package com.lyc.login.controller;

import com.lyc.common.utils.MD5Util;
import com.lyc.user.entity.User;
import com.lyc.user.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * @Author YooLin
 * @Date 2017/7/23 17:09
 * @Description 登录页面
 */
@Controller
@RequestMapping("login")
public class LoginController {

//    @Autowired
//    private IUserService userService;

    private static final String LOGIN_SUCCESS = "1";

    /**
     * 登录页面
     * @return
     */
    @RequestMapping
    public String login() {
        return "login";
    }

    /**
     * 登录校验
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    @RequestMapping("/checkLogin")
    @ResponseBody
    public int checkLogin(HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        //使用shiro登录
        try {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String rm = request.getParameter("rm");//记住我
            Subject subject = SecurityUtils.getSubject();
            //已经登录isAuthenticated会返回true
            if (subject.isAuthenticated()){
                return -1;
            }
            boolean rememberMe = LOGIN_SUCCESS.equals(rm);
            subject.login(new UsernamePasswordToken(username,password,rememberMe));
            subject.getSession().setTimeout(1800000);//500小时
            return 1;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return -1;
        }

//        String username = request.getParameter("username");
//        String password = request.getParameter("password");
//        User u = userService.findByUsername(username);
//        if (u != null) {
//            if (MD5Util.checkPassword(password,u.getPassword())) {
//                //将用户信息保存至session中
//                request.getSession().setAttribute("userInfo", u);
//                return 1;
//            }
//        }
//        return -1;
    }
}
